<template>
  <FCPage direction="row">
    <a-spin :spinning="spinningLoading">
      <FCTab
        :tabList="tabList"
        :activeKey="activeKey"
        :onChange="handleTabChange"
      >
        <FCPage
          :slot="1"
          direction="column"
          class="backgroundColor"
        >
          <!-- 银行划盘支付 -->
          <FCLayout :flex="1">
            <FCForm
              ref="bankPaymentForm"
              v-bind="bankFormConfig"
              :dataset="dsBank"
            />
          </FCLayout>
          <FCLayout
            height="40px"
            alignItem="center"
          >
            <FCButton
              type="primary"
              value="支付"
              @click="handlePayment"
              :loading="paymentButtonLoading"
              :disabled="paymentStatus == '7' && paymentButtonDisabled"
              :style="{width: '120px'}"
            />
          </FCLayout>
        </FCPage>
        <!-- 银企直连支付 -->
        <FCPage
          :slot="2"
          direction="row"
        >
          <FCLayout
            :flex="1"
            class="backgroundColor marginRight"
          >
            <FCPage
              direction="column"
              style="height: 350px"
            >
              <FCLayout class="marginBottom">
                <a-space>
                  <FCButton
                    type="primary"
                    value="确定"
                    @click="handleSure"
                  />
                  <FCButton
                    :disabled="tableDataSource.length < 1"
                    type="primary"
                    value="明细重置"
                    @click="handleReset"
                  />
                  <FCButton
                    :disabled="tableDataSource.length < 1"
                    value="取消"
                    @click="handleCancle"
                  />
                  <FCButton
                    :loading="submitLoading"
                    :disabled="tableDataSource.length < 1"
                    value="提交"
                    @click="handleSubmit"
                  />
                </a-space>
              </FCLayout>
              <FCLayout>
                <FCTable
                  :scroll="tableDataSource.length > 0 ? { x: '100%',y: 130}: { x: '100%' }"
                  :fields="tableFields"
                  :dataset="dsBankCompany"
                  :customRow="customRow"
                >
                  <template slot="footer"> 合计：{{ totalPaymentMoney.toFixed(2) }} </template>
                </FCTable>
              </FCLayout>
            </FCPage>
          </FCLayout>
          <FCLayout
            style="height: auto"
            :flex="1"
            class="backgroundColor"
          >
            <FCForm
              style="margin-top: 40px;width: 88%"
              v-bind="bankCompanyFormConfig"
              :dataset="dsBankCompany"
            />
          </FCLayout>
        </FCPage>

      </FCTab>
    </a-spin>
  </FCPage>
</template>

<script>
import FCDataset from '@/vendors/fc-dataset/FCDataset'
import FCTab from '@/vendors/fc-ui/src/controls/FCTab.vue'
import FCForm from '@/vendors/fc-ui/src/form/FCForm.vue'
import FCButton from '@/vendors/fc-ui/src/controls/FCButton.vue'
import FCTable from '@/vendors/fc-ui/src/table/FCTable.vue'
import { drp_currency, drp_type } from '../../data'
import moment from 'moment'
import {
  paymentApplicationForm,
  submitBankCompany,
} from '@/apis/paymentApplicationFormApi'

export default {
  name: 'paymentWay',
  components: {
    FCTab,
    FCForm,
    FCButton,
    FCTable,
  },
  props: {
    nowRecord: Object,
    activeKey: {
      type: [String, Number],
      default: '1',
    },
    nowRecordPaymentstatus: [String, Number],
    selectedRowsExchangecurrencycode: [String, Number],
    selectedRows: Array,
  },
  data() {
    const dsBank = new FCDataset({
      fields: [
        { name: 'bankaccountno', type: 'string' },
        { name: 'accountno', type: 'string' },
        { name: 'paymenttime', type: 'string' },
        { name: 'currencycode', type: 'string' },
        { name: 'amount', type: 'number' },
        { name: 'memo', type: 'string' },
        { name: 'exchangeflag', type: 'string' },
        { name: 'exchangerate', type: 'number' },
      ],
      datas: [],
    })
    const dsBankCompany = new FCDataset({
      fields: [
        { name: 'accountname', type: 'string' },
        { name: 'amount', type: 'number' },
        { name: 'currencycode', type: 'string' },
        { name: 'inpaymentmethod', type: 'string' },
        { name: 'memo', type: 'string' },
        { name: 'customername', type: 'string' },
        { name: 'custaccountno', type: 'string' },
        { name: 'custbankno', type: 'string' },
        { name: 'bankname', type: 'string' },
        { name: 'bankprovince', type: 'string' },
        { name: 'bankcity', type: 'string' },
      ],
      datas: [],
    })
    return {
      totalPaymentMoney: 0,
      paymentButtonDisabled: false,
      bankPaymentData: this.nowRecord,
      submitLoading: false,
      spinningLoading: false,
      paymentButtonLoading: false,
      selectedRowsData: this.selectedRows,
      tableDataSource: [],
      tableFields: [
        {
          title: '账户名称',
          name: 'accountname',
          width: 200,
          ellipsis: true,
        },
        {
          title: '应付金额',
          name: 'amount',
          width: 200,
          ellipsis: true,
        },
        {
          title: '应付币种',
          name: 'currencycode',
          width: 200,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_currency.filter((item) => item.value == text)[0]?.label ||
              '未知'
            )
          },
        },
        {
          title: '支付方式',
          name: 'inpaymentmethod',
          width: 200,
          ellipsis: true,
          customRender: (text) => {
            return (
              drp_type.filter((item) => item.value == text)[0]?.label || '未知'
            )
          },
        },
        {
          title: '客户名称',
          name: 'customername',
          width: 200,
          ellipsis: true,
        },
        {
          title: '支付原因',
          name: 'memo',
          width: 200,
          ellipsis: true,
        },
      ],
      bankFormConfig: {
        cols: 2, //每行布局几列
        labelCol: 8,
        wrapperCol: 16,
        labelAlign: 'right', //对齐方式
        fields: [
          {
            name: 'bankaccountno',
            title: '流水单实际编号',
            controlType: 'input',
            rules: [{ required: true, message: '流水单实际编号不能为空！' }],
          },
          {
            name: 'accountno',
            title: '太保银行账号',
            controlType: 'selectTable',
            controlProps: {
              tableProps: {
                fields: [
                  {
                    name: 'accountName',
                    title: '账户名称',
                  },
                  {
                    name: 'accountno',
                    title: '账户代码',
                  },
                  {
                    name: 'unitcode',
                    title: '财务机构',
                  },
                ],
              },
              optionsLabel: 'accountno',
              optionsValue: 'accountno',
              optionsApi: () => {
                return [
                  {
                    accountName: '资金往来户-8935',
                    accountno: '310066726018001458935',
                    unitcode: '产险公司总部',
                  },
                  {
                    accountName: '河北分公司本部',
                    accountno: '310066726018001458936',
                    unitcode: '石家庄分公司本部',
                  },
                  {
                    accountName: '见费出单户(促销活动)',
                    accountno: '310066726018001458937',
                    unitcode: '产险公司总部',
                  },
                ]
              },
            },
            rules: [{ required: true, message: '太保银行账号不能为空！' }],
          },
          {
            name: 'currencycode',
            title: '币种',
            controlType: 'select',
            controlProps: {
              disabled: true,
              optionsApi: () => {
                return [...drp_currency]
              },
            },
            rules: [{ required: true, message: '币种不能为空！' }],
          },
          {
            name: 'paymenttime',
            title: '实际付款日期',
            controlType: 'datePicker',
            controlProps: {
              format: 'YYYY-MM-DD',
              style: { width: '100%' },
            },
          },

          {
            name: 'amount',
            title: '金额',
            controlType: 'inputNumber',
            controlProps: {},
            rules: [{ required: true, message: '金额不能为空！' }],
          },
          {
            name: 'memo',
            title: '备注',
            controlType: 'input',
          },
          {
            name: 'exchangeflag',
            title: '购汇标识',
            controlType: 'checkbox',
            controlProps: {
              onValue: '1',
              offValue: '0',
            },
          },
          {
            name: 'exchangerate',
            title: '汇率(美元兑人民币)',
            controlType: 'inputNumber',
          },
        ],
      },
      bankCompanyFormConfig: {
        cols: 2, //每行布局几列
        labelCol: 9,
        wrapperCol: 15,
        labelAlign: 'right', //对齐方式
        fields: [
          {
            name: 'customername',
            title: '客户名称',
            // span: 24,
            // labelCol: 4,
            // wrapperCol: 20,
            controlType: 'input',
          },
          {
            name: 'custaccountno',
            title: '客户账号',
            controlType: 'input',
          },
          {
            name: 'custbankno',
            title: '客户银行代码',
            controlType: 'input',
          },
          {
            name: 'bankname',
            title: '开户行',
            // span: 24,
            // labelCol: 4,
            // wrapperCol: 20,
            controlType: 'input',
          },
          {
            name: 'bankprovince',
            title: '开户行所在省',
            controlType: 'input',
          },

          {
            name: 'bankcity',
            title: '开户行所在市',
            controlType: 'input',
          },
        ],
      },
      index: 0,
      dsBankCompany,
      dsBank,
      tabList: [
        { key: '1', title: '银行划盘支付' },
        { key: '2', title: '银企直连支付' },
      ],
      paymentStatus: this.nowRecordPaymentstatus,
      recordApi: false,
    }
  },
  watch: {
    nowRecord(value) {
      this.bankPaymentData = value
    },
    nowRecordPaymentstatus(value) {
      this.paymentStatus = value
      this.paymentButtonDisabled = false
    },
    selectedRowsExchangecurrencycode(value) {
      this.setExchangecurrencycodeFun(value)
    },
    selectedRows(arr) {
      this.selectedRowsData = arr
    },
  },
  mounted() {
    this.setExchangecurrencycodeFun(this.selectedRowsExchangecurrencycode)
  },
  methods: {
    handleResetData() {
      const paymenttime = moment()
      this.dsBank.clear()
      this.dsBank.setFieldsValue({ paymenttime })
    },
    handleBankPayment() {
      this.paymentButtonDisabled = true
      this.dsBank.clear()
      this.dsBank.addRecord(this.bankPaymentData)
    },
    handlePayment() {
      if (this.selectedRowsData.length < 1)
        return this.$message.warning('没有要操作的数据！')
      this.$refs.bankPaymentForm.form.validateFields((err) => {
        if (!err) {
          this.paymentButtonLoading = true
          const formData = this.dsBank.getValues()
          paymentApplicationForm(formData).then((res) => {
            this.paymentButtonLoading = false
            if (!res.error) {
              this.$message.success('支付成功！')
              this.handleResetData()
              this.$emit('paymentSuccess')
            }
          })
        }
      })
    },
    handleCancle() {
      const _this = this
      this.$confirm({
        title: '确定要取消吗？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          _this.resetBankCompany()
          _this.$emit('cancelSelect')
        },
      })
    },
    async handleSubmit() {
      this.submitLoading = true
      const res = await submitBankCompany()
      this.submitLoading = false
      console.log('>>> handleSubmit-res', res);
      if (!res.error) {
        this.$message.success('提交成功！')
        this.resetBankCompany()
        this.$emit('submitSuccess')
      }
    },
    handleReset() {
      const _this = this
      this.$confirm({
        title: '确定要重置吗？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          _this.resetBankCompany()
        },
      })
    },
    resetBankCompany() {
      this.dsBankCompany.clear()
      this.totalPaymentMoney = 0
      this.tableDataSource = []
      this.index = 0
      this.selectedRowsData = this.selectedRows
      console.log('>>>> reset');
    },
    handleSure() {
      this.totalPaymentMoney = 0
      if (this.selectedRowsData.length < 1)
        return this.$message.warning('请选择支付数据！')
      this.dsBankCompany.clear()
      this.selectedRowsData.forEach((item) => {
        this.totalPaymentMoney += item?.amount || 0
        this.dsBankCompany.addRecord(item)
      })
      this.tableDataSource = this.selectedRowsData
    },
    resetTab() {
      this.dsBank.clear()
      this.dsBankCompany.clear()
      this.recordApi = false
    },
    setExchangecurrencycodeFun(currencycode) {
      const paymenttime = moment().format('YYYY-MM-DD')
      this.dsBank.clear()
      this.dsBank.setFieldsValue({ currencycode, paymenttime })
    },
    handleTabChange(data) {
      console.log('>>>> tab切换：', data)
    },
    customRow(record, index) {
      return {
        style: {
          'background-color': index === this.index ? '#e6f7ff' : '',
        },
        on: {
          click: () => {
            this.index = index
            this.dsBankCompany.currentKey =
              this.dsBankCompany.getRecordAt(index).key
          },
        },
      }
    },
  },
}
</script>

<style lang="less" scoped>
</style>>